package com.wzy.business.store.main.fragment

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import com.bumptech.glide.Glide
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.wangzhenyu.common.base.BasePreImpl
import com.wangzhenyu.common.base.BasePresenter
import com.wangzhenyu.common.base.delegate.BaseVBPFragment
import com.wangzhenyu.common.util.exts.gone
import com.wangzhenyu.common.util.exts.visible
import com.wangzhenyu.common.util.log.LogUtil
import com.wzy.business.R
import com.wzy.business.base.photo.APIService
import com.wzy.business.base.photo.CommonRepository
import com.wzy.business.base.photo.DuckManager
import com.wzy.business.base.photo.bean.LoginDuck
import com.wzy.business.databinding.FragmentShopPhotoBinding
import com.wzy.business.store.commonpop.MediaMenuPop
import com.wzy.business.store.main.ApplyShopInfoActivity
import com.wzy.business.store.main.ApplyShopInfoViewModel
import com.wzy.business.util.OtherUtils
import com.wzy.business.util.photo.GlideEngine
import id.zelory.compressor.Compressor
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.security.Permission
import id.zelory.compressor.constraint.format

class ShopPhotoFragment : BaseVBPFragment<FragmentShopPhotoBinding, BasePresenter>() {

    private val model by activityViewModels<ApplyShopInfoViewModel>()

    private var type: Int = 0

    override fun createPresenter() = BasePreImpl(this)

    private var requestMultiplePermissions: ActivityResultLauncher<Array<String>>? = null

    override fun getBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ) = FragmentShopPhotoBinding.inflate(inflater, container, false)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestMultiplePermissions =  registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            permissions.entries.forEach {
                LogUtils.d(it.key + " " + it.value)
            }
        }
    }

    override fun initViewsAndData(rootView: View) {
        type = arguments?.getInt("type") ?: 0

        when (type) {

            ApplyShopInfoActivity.HIRE -> {
                mbinding.textView.visible()
                mbinding.linearLayout.gone()
                mbinding.imageView.visible()
                model.applyShopInfo.value?.bizplacepic?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.imageView)
                }
                model.setTitle("上传店铺租聘合同")
            }

            ApplyShopInfoActivity.LICENSE -> {
                mbinding.textView.visible()
                mbinding.linearLayout.gone()
                mbinding.imageView.visible()
                model.applyShopInfo.value?.licenceImg?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.imageView)
                }
                model.setTitle("上传营业执照")
            }

            ApplyShopInfoActivity.TAXES -> {
                mbinding.textView.visible()
                mbinding.linearLayout.gone()
                mbinding.imageView.visible()
                model.applyShopInfo.value?.taxes_certificate_img?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.imageView)
                }
                model.setTitle("上传税务登记证照片")
            }

            ApplyShopInfoActivity.ORGAN -> {
                mbinding.textView.visible()
                mbinding.linearLayout.gone()
                mbinding.imageView.visible()
                model.applyShopInfo.value?.orgcodepic?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.imageView)
                }
                model.setTitle("上传组织机构代码证照片")
            }

            ApplyShopInfoActivity.SHOP_FRONT -> {
                mbinding.linearLayout.visibility = View.VISIBLE
                mbinding.imageView.visibility = View.GONE
                model.applyShopInfo.value?.shopPhotoFront?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.shopFront)
                }
                model.applyShopInfo.value?.shopPhotoInside?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.shopInside)
                }
                model.setTitle("上传店铺照片")
            }

            ApplyShopInfoActivity.OTHER_PIC -> {
                mbinding.textView.visible()
                mbinding.linearLayout.visibility = View.VISIBLE
                mbinding.imageView.visibility = View.GONE
                model.applyShopInfo.value?.other_Pic_One?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.shopFront)
                }
                model.applyShopInfo.value?.other_Pic_Two?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.shopInside)
                }
                mbinding.textView1.visibility = View.INVISIBLE
                mbinding.textView2.visibility = View.INVISIBLE
                model.setTitle("上传其他资质照片")
            }

            ApplyShopInfoActivity.FOOD_ALLOW -> {
                mbinding.textView.visible()
                mbinding.linearLayout.visibility = View.GONE
                mbinding.imageView.visibility = View.VISIBLE
                model.applyShopInfo.value?.foodAllow?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.imageView)
                }
                model.setTitle("上传食品经营许可证照片")
            }

            ApplyShopInfoActivity.PICTURE_COMPANY_ACCOUNT -> {
                mbinding.linearLayout.visibility = View.GONE
                mbinding.imageView.visibility = View.VISIBLE
                model.companyAccount.value?.bankUrls?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.imageView)
                }
                model.setTitle("上传开户许可证照片")
            }

            ApplyShopInfoActivity.PICTURE_PERSONAL_ACCOUNT -> {
                mbinding.linearLayout.visibility = View.GONE
                mbinding.imageView.visibility = View.VISIBLE
                model.personalAccount.value?.bankUrls?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.imageView)
                }
                model.setTitle("上传银行卡正面照")
            }

            ApplyShopInfoActivity.AUTHOR_PIC -> {
                mbinding.linearLayout.visibility = View.GONE
                mbinding.imageView.visibility = View.VISIBLE
                model.applyShopInfo.value?.authorpic?.also {
                    Glide.with(requireActivity()).load(it).into(mbinding.imageView)
                }
                model.setTitle("上传商户签约承诺函")
            }

            else -> {

            }
        }

        initListener()


    }

    private fun initListener() {

        //可以删除营业执照
        if (type == ApplyShopInfoActivity.LICENSE) {
            mbinding.deleteTextView.visible()
            mbinding.deleteTextView.setOnClickListener {

                model.applyShopInfo.value?.licenceImg = null
                //营业执照没了，相关的数据也需要去除
                model.applyShopInfo.value?.also { info ->
                    info.companyName = null
                    info.licenseNum = null
                    info.licenceEnd = null
                    info.scope = null
                    info.regMoney = 1
                }
                model.companyAccount.value?.openAccountName = null
                mbinding.imageView.setImageBitmap(null)
                mbinding.imageView.setImageBitmap(
                    BitmapFactory.decodeResource(
                        resources,
                        R.mipmap.main_shop_image_upload,
                        null
                    )
                )
            }
        }

        if (!model.shopOpenOrNot) {
            mbinding.shopFront.setOnClickListener {
                setOnClickForPhoto(type, 1)
            }

            mbinding.shopInside.setOnClickListener {
                setOnClickForPhoto(type, 2)
            }

            //只传一张图片时
            mbinding.imageView.setOnClickListener {
                setOnClickForPhoto(type, 1)
            }
        }

        mbinding.backTextView.setOnClickListener {
            findNavController().navigateUp()
        }
    }

    private fun setOnClickForPhoto(type: Int, number: Int) {
        val pop =
            MediaMenuPop(
                requireActivity(),
                MediaMenuPop.TYPE_SELECT_PHOTO or MediaMenuPop.TYPE_PLAY_PHOTO
            )
        pop.setOnClickListener { flags ->
            when (flags) {
                MediaMenuPop.TYPE_SELECT_PHOTO -> {
                    PictureSelector.create(this)
                        .openGallery(SelectMimeType.ofImage())
                        .setMaxSelectNum(1)
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .forResult(object : OnResultCallbackListener<LocalMedia> {

                            override fun onResult(result: ArrayList<LocalMedia>?) {
                                val localMedia = result?.get(0)
                                showAndUploadImage(localMedia, type, number)
                            }

                            override fun onCancel() {
                                //取消
                            }
                        })

                }

                MediaMenuPop.TYPE_PLAY_PHOTO -> {
                    PictureSelector.create(this)
                        .openCamera(SelectMimeType.ofImage())
                        .forResult(object : OnResultCallbackListener<LocalMedia?> {

                            override fun onResult(result: ArrayList<LocalMedia?>?) {
                                // 结果回调
                                val localMedia = result?.get(0)
                                showAndUploadImage(localMedia, type, number)
                            }

                            override fun onCancel() {
                                // 取消
                            }
                        })
                }

            }
        }
        pop.showPopupWindow()
    }

    private fun showAndUploadImage(localMedia: LocalMedia?, type: Int, number: Int) {

        lifecycleScope.launch {
            //获取token
            val token = DuckManager.getDuckLoginInfo()?.data?.token
            if (token.isNullOrEmpty()) {
                val temp =
                    CommonRepository.getInstance("").getRetrofit()?.create(APIService::class.java)
                        ?.login(LoginDuck("923680072@qq.com", "zhenyuwanghhxx88"))
                if (temp != null) {
                    DuckManager.setDuckLoginInfo(temp)
                } else {
                    showToast("登陆失败")
                }
            }

            //开始上传图片
            var file: File = OtherUtils.getImageFile(localMedia) ?: return@launch
            BitmapFactory.decodeFile(file.absolutePath)
            if (file.exists()) {
                LogUtils.dTag("WZYTest", "存在")
                LogUtils.dTag("WZYTest",file.absolutePath)
            } else {
                LogUtils.dTag("WZYTest", "不存在")
                LogUtils.dTag("WZYTest",file.absolutePath)
            }

            //处理图片
            var imageType = "image/png"
            if (file.name.endsWith("jpg")) {
                imageType = "image/jpg"
            } else if (file.name.endsWith("jpeg")) {
                imageType = "image/jpeg"
            }

            file = if (file.name.endsWith("png")) {
                Compressor.compress(Utils.getApp(), file) {
                    format(Bitmap.CompressFormat.PNG)
                }
            } else {
                Compressor.compress(Utils.getApp(), file)
            }

            val requestFile: RequestBody = file.asRequestBody(imageType.toMediaTypeOrNull())

            val multipartBody = MultipartBody.Part.createFormData("file", file.name, requestFile)


            val uploadFile =
                CommonRepository.getInstance("").getRetrofit()?.create(APIService::class.java)
                    ?.uploadImage(multipartBody)


//            if (uploadFile.isSuccess) {
//
//
//                when (type) {
//                    ApplyShopInfoActivity.SHOP_FRONT -> {
//
//                    }
//
//                    ApplyShopInfoActivity.OTHER_PIC -> {
//
//                    }
//
//                    ApplyShopInfoActivity.HIRE -> {
//
//                    }
//
//
//                }
//
//
//
//                showToast("上传成功")
//            }
        }


    }


}